<?php

namespace app\controller;

use app\model\Tweet;
use app\model\User;

class HomeController extends BaseController
{
    /**
     * 显示主时间线/信息流
     */
    public function index(): void
    {
        $this->requireLogin();
        $currentUserId = $this->getCurrentUserId();

        // 获取当前用户关注的人的ID列表
        $followingIds = $_SESSION['follows'][$currentUserId] ?? [];
        $followingIds[] = $currentUserId; // 时间线也应该包含自己的帖子

        $allTweets = Tweet::all();

        $timelineTweets = array_filter($allTweets, function (Tweet $tweet) use ($followingIds) {
            return in_array($tweet->user_id, $followingIds) && $tweet->parent_id === null;
        });

        // 按时间戳降序排序
        usort($timelineTweets, function (Tweet $a, Tweet $b) {
            return $b->timestamp - $a->timestamp;
        });

        // 获取未读通知
        $notifications = $this->getUnreadNotifications();

        $this->render('home/index', [
            'tweets' => $timelineTweets,
            'notifications' => $notifications,
        ]);
    }
}
